import requests
import json
from time import sleep
import re
import html
from 测试集评估.主要.data_v_1_0 import load_question_only
from tqdm import tqdm

"""
    v0.1:
    4/24
    去掉html
    去掉思维链，标记是<details>，对于聊天助手够用了，后面要做成可选
    4/25
    测试聊天助手，
    还需要做成跑一条写一条的方式
    
    
"""

# http://10.10.93.198/v1
API_URL = "http://10.10.93.198:8090/v1/chat-messages"
API_KEY = "app-SRoouEPrCLS0UW1uuwEThKhG"  # 替换成你的真实 API 密钥
HEADERS = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json"
}

# 选定智能体
sheet="聊天助手"

# 测试集
test_queries=load_question_only(sheet=sheet)
# 回答
results = []

# 创建进度条对象
progress_bar = tqdm(total=len(test_queries))

for i, query in enumerate(test_queries):
    payload = {
        "inputs": {},
        "query": query,
        "response_mode": "blocking",
        "conversation_id": "",
        "user": "abc-123",
        "files": []
    }

    try:
        response = requests.post(API_URL, headers=HEADERS, json=payload, timeout=90)
        response.raise_for_status()
        data = response.json()
        print(1111,data,11111)  # TODO 测试
        answer = data.get("answer", "")
        # print(answer)# TODO 测试
        # 还需html解析，还需去掉思维链

        # 1. 去除思维链： < details > 标签块（可选）
        cleaned = re.sub(r"<think.*?</think>", "", answer, flags=re.DOTALL)
        # 2. 去除所有 HTML 标签
        cleaned = re.sub(r"<[^>]+>", "", cleaned)
        # 3. 将转义字符还原（如 \n, \", &nbsp; 等）
        cleaned_answer = html.unescape(cleaned)

    except Exception as e:
        cleaned_answer = f"[Error] {e}"

    results.append({
        "query": query,
        "answer": cleaned_answer
    })

    print(f"query: {query},answer: {cleaned_answer}")

    # 更新进度
    progress_bar.update(1)
    sleep(1)  # 可选：避免请求过快

progress_bar.close()
# 保存为 JSON
with open(f"./data/{sheet}_answers.json", "w", encoding="utf-8") as f:
    json.dump(results, f, ensure_ascii=False, indent=2)

print(f"{sheet}所有查询已完成，答案已保存到 {sheet}_answers.json")
